package org.devgframwork.datasync.core.support;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.Message;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.devgframwork.datasync.core.entity.CanalConfig;
import org.devgframwork.datasync.core.support.init.rabbitmq.RabbitQueueInit;
import org.devgframwork.datasync.core.utils.CommonUtil;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author devg @Date 2018/11/25 11:41
 */
@Slf4j
public class DataSourceCanal implements Runnable {

    private CanalConfig canalConfig;

    public DataSourceCanal(CanalConfig canalConfig) {
        this.canalConfig = canalConfig;
    }

    @Override
    public void run() {
        initCanal();
    }

    public void initCanal() {
        CanalConnector connector =
                CanalConnectors.newSingleConnector(new InetSocketAddress(canalConfig.getIp(), canalConfig.getPort()), canalConfig.getType(), "", "");
        int batchSize = 1000;
        try {
            System.out.println("canal start up success...");
            connector.connect();
//      connector.subscribe(canalConfig.getExtract());
            connector.subscribe(".*\\..*");
            //connector.subscribe("datad.tb_user_agent,datad.tb_user_role");
            connector.rollback();
            while (true) {
                Message message = connector.getWithoutAck(batchSize);
                long batchId = message.getId();
                int size = message.getEntries().size();
                if (batchId == -1 || size <= 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        printEntry(message.getEntries());
                        connector.ack(batchId);
                    } catch (Exception e) {
                        connector.rollback(batchId);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            connector.disconnect();
        }
    }

    private void printEntry(List<CanalEntry.Entry> entrys) throws Exception {
        String connectionName = canalConfig.getConnectionName();
        Channel channel = DataSourceMemory.connectionChannelMap.get(connectionName);
        for (CanalEntry.Entry entry : entrys) {
            if (entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONBEGIN
                    || entry.getEntryType() == CanalEntry.EntryType.TRANSACTIONEND) {
                continue;
            }
            String tableName = entry.getHeader().getTableName();
            CanalEntry.RowChange rowChage = CanalEntry.RowChange.parseFrom(entry.getStoreValue());
            CanalEntry.EventType eventType = rowChage.getEventType();
            for (CanalEntry.RowData rowData : rowChage.getRowDatasList()) {
                JSONObject json = new JSONObject();
                List<CanalEntry.Column> columns = rowData.getAfterColumnsList();
                if (eventType == CanalEntry.EventType.DELETE) {
                    columns = rowData.getBeforeColumnsList();
                }
                for (CanalEntry.Column column : columns) {
                    json.put(column.getName(), column.getValue());
                }
                if (eventType == CanalEntry.EventType.DELETE) {
                    json.put(CommonUtil.CANALEVENTTYPE, CommonUtil.DELETE);
                    json.put("es_delete", "1");
                } else if (eventType == CanalEntry.EventType.INSERT) {
                    json.put(CommonUtil.CANALEVENTTYPE, CommonUtil.INSERT);
                } else {
                    json.put(CommonUtil.CANALEVENTTYPE, CommonUtil.UPDATE);
                }
                json.put("CONNECTION_NAME", connectionName);
                json.put("TABLE_NAME", tableName);
                String exchange = connectionName + RabbitQueueInit.suffixExchange;
                String routingKey = "ds_".concat(tableName);
                channel.basicPublish(exchange, routingKey, null, json.toJSONString().getBytes(StandardCharsets.UTF_8));
            }
        }
    }

    private void printColumn(String tableName, List<CanalEntry.Column> columns) throws Exception {
        for (CanalEntry.Column column : columns) {
//      System.out.print(
//          column.getName() + ":" + column.getValue() + " update=" + column.getUpdated() + ",");
            System.out.print(
                    column.getName() + ":" + column.getValue() + ",");
        }
        System.out.println();
    }

    private void canalInsert(String tableName, List<CanalEntry.Column> columns) throws Exception {
        JSONObject json = new JSONObject();
        for (CanalEntry.Column column : columns) {
            json.put(column.getName(), column.getValue());
        }
    }

    private void canalUpdate(String tableName, List<CanalEntry.Column> columns) throws Exception {
        JSONObject json = new JSONObject();
        for (CanalEntry.Column column : columns) {
            json.put(column.getName(), column.getValue());
        }
    }

    private void canalDelete(String tableName, List<CanalEntry.Column> columns) throws Exception {
        JSONObject json = new JSONObject();
        for (CanalEntry.Column column : columns) {
            json.put(column.getName(), column.getValue());
        }
    }
}
